package com.qcby.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.qcby.admin.utils.WebUtils;
import com.qcby.framwork.utils.AppHttpCodeEnum;
import com.qcby.framwork.utils.ResponseResult;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse
            response, AuthenticationException authException) throws IOException,
            ServletException {
        authException.printStackTrace();
//InsufficientAuthenticationException
//BadCredentialsException
        ResponseResult result = null;
        //判断异常类型
        if(authException instanceof BadCredentialsException){//登录错误
            result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(),authException.getMessage());
        }else if(authException instanceof InsufficientAuthenticationException){//未登录
            result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }else{//未知错误
            result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(),"认证或授权失败");
        }
//响应给前端
        WebUtils.renderString(response, JSON.toJSONString(result));
    }
}
